﻿using System;
using System.Web.Mvc;
using Chatu.ControlLider.Web.Models.Common;
using Chatu.ControlLider.Web.Models.Domain;
using Chatu.ControlLider.Web.Models.Repositories;

namespace Chatu.ControlLider.Web.Controllers
{
    [Authorize]
    public partial class HomeController : Controller
    {
        private readonly IEmployeeRepository _repository;

        public HomeController() : this(new SqlEmployeeRepository())
        { }

        public HomeController(IEmployeeRepository repository)
        {
            _repository = repository;
        }

        public virtual ActionResult Index()
        {
            if (User.IsInRole(AppConstants.ADMINISTRATOR_ROLE))
                return RedirectToAction(MVC.Employee.Index());

            return View(_repository.GetEmployeeLaborDay(User.Identity.Name));
        }

        public virtual ActionResult Attendance(string cedula)
        {
            if (Request.Form["entrada"] != null)
                _repository.RegiterEntrance(cedula, _repository.CurrentTimeZone);
            else
            {
                EmployeeLaborDay emp = _repository.GetEmployeeLaborDay(User.Identity.Name);

                DateTime inDate = emp.LaborData.InDate.Value;
                DateTime outDate = _repository.CurrentTimeZone;

                double guardia = 0.0;
                double bono = 0.0;

                //guardia
                TimeSpan diff = outDate - inDate;

                int hours = diff.Hours;

                if (hours > 6)
                {
                    hours = hours - 6;
                    guardia = Math.Ceiling(hours/3.0)/2.0;
                }

                //bono
                TimeSpan inTime = inDate.TimeOfDay.Duration();
                TimeSpan outTime = outDate.TimeOfDay.Duration();
                TimeSpan t = new TimeSpan(19, 0, 0); //7pm

                if (inTime > t)
                    t = inTime;

                if (outTime > t)
                {
                    TimeSpan timeDiff = outTime - t;
                    bono = double.Parse(string.Format("{0},{1}", timeDiff.Hours, timeDiff.Minutes));
                }

                _repository.RegisterExit(cedula, outDate, guardia, bono, 1);
            }

            return RedirectToAction(MVC.Home.Index());
        }
    }
}